<?php
namespace app\cut_pic\controller;

use think\Controller;
use think\Db;
use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class Index extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    public function image_insert()
    {
        $data = $this->request->post();
//        echo $image;
        $result = $this->validate($data, 'Vali.add');
        if (true !== $result) {
            $this->error($result);
        } else {
            $data['utime'] = time();
            $image = Db::name('image');
            $res = $image->insert($data);
            if ($res) {
                $this->success('添加图片成功', 'index/index');
            } else {
                $this->error($image->getError());
            }
        }

    }

    //上传原图
    public function pre_img_upload()
    {
        $file = request()->file('imgFile');

        // 移动到框架应用根目录/public/uploads/ 目录下,命名为hello
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/pre_pic','hello');
        if ($info) {
            $savename = $info->getSaveName();

            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            return json(array('error' => 0, 'url' => $savename, 'title' => $savename));
        } else {
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }


    //图像裁剪
    public function img_cut()
    {
        $pre_pic = $this->request->post('pre_pic');
        $cut_info = $this->request->post('info/a');
        $image = \think\Image::open('uploads/pre_pic/' . $pre_pic);
        // 按照原图的比例生成页面显示的大小并保存为thumb.png
        $image->thumb($cut_info['scaleWidth'], $cut_info['scaleHeight'])->save('uploads/thumb_pre_pic/thumb.png');
        $thumb = \think\Image::open('uploads/thumb_pre_pic/thumb.png');
        $data['time'] = time();
        //将图片裁剪为300x300并保存为crop.png
        $res = $thumb->text('文字', 'static/font/HYQingKongTiJ.ttf', 20, '#ffffff')->crop($cut_info['width'], $cut_info['height'], $cut_info['left'], $cut_info['top'])->save('uploads/cut_img/' . $data['time'] . '.png');
        $crop = \think\Image::open('uploads/cut_img/' . $data['time'] . '.png');
        $size = filesize('uploads/cut_img/' . $data['time'] . '.png');
        $data['size'] = haveSize($size);
        if ($res) {
            return json($data);
        }
    }

    public function index2()
    {
        return $this->fetch();
    }

    public function qiniu_upload()
    {
        if (request()->isPost()) {
//            print_r($_FILES);die();
            $file = request()->file('imgFile');
            // 要上传图片的本地路径
            $filePath = $file->getInfo('tmp_name');
//            print_r($filePath);die();
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
            // 上传到七牛后保存的文件名
            $key = $file->getInfo('name');
            require_once APP_PATH . '/../vendor/qiniu/autoload.php';
            // 需要填写你的 Access Key 和 Secret Key
            $accessKey = config('ACCESSKEY');
            $secretKey = config('SECRETKEY');
            // 构建鉴权对象
            $auth = new Auth($accessKey, $secretKey);
            // 要上传的空间
            $bucket = config('BUCKET');
            $domain = config('DOMAIN');
            $token = $auth->uploadToken($bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return ["error" => 1, "url" => $err, "title" => ""];
            } else {
                //返回图片的完整URL
                return json(["error" => 0, "url" => "上传完成", "title" => ($domain . '/' . $ret['key'])]);
            }
        }
    }


    public function show_qiniu_list()
    {
        require_once APP_PATH . '/../vendor/qiniu/autoload.php';
        $accessKey = config('ACCESSKEY');
        $secretKey = config('SECRETKEY');
        $auth = new Auth($accessKey, $secretKey);
        $bucketMgr = new BucketManager($auth);
        $domain = config('DOMAIN');
        // 要列取的空间名称
        $bucket = config('BUCKET');
        // 要列取文件的公共前缀
        $prefix = '';
        // 上次列举返回的位置标记，作为本次列举的起点信息。
        $marker = '';
        // 本次列举的条目数
        $limit = '';
        // 列举文件
        list($iterms, $marker, $err) = $bucketMgr->listFiles($bucket, $prefix, $marker, $limit);
        if ($err !== null) {
            echo "\n====> list file err: \n";
            var_dump($err);
        } else {
            echo "Marker: $marker\n";
            echo "\nList Iterms====>\n";
            foreach($iterms as &$i){
                $i['url'] = $domain . '/' .$i['key'];
            }
            var_dump($iterms);
        }
    }

    public function upload(){
        $file = request()->file('imgFile');
        $path =  'uploads/pre_pic/';

        //本地上传
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS .$path);
        if ($info) {
            $savename = $info->getSaveName();
            $size = haveSize( $info->getSize());


            //七牛上传
            $filePath = $path.$savename;
            // 上传到七牛后保存的文件名
            $name = str_replace("\\","/",$savename);
            $key = 'uploads/pre_pic/'.$name;
            require_once APP_PATH . '/../vendor/qiniu/autoload.php';
            // 需要填写你的 Access Key 和 Secret Key
            $accessKey = config('ACCESSKEY');
            $secretKey = config('SECRETKEY');
            // 构建鉴权对象
            $auth = new Auth($accessKey, $secretKey);
            // 要上传的空间
            $bucket = config('BUCKET');
            $domain = config('DOMAIN');
            $token = $auth->uploadToken($bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err == null) {
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                return json(array('error' => 0, 'url' => $savename, 'title' =>$path.$savename,'width'=>$ret['key'],'height'=>$domain,'border'=>$size));
            } else {
                // 上传失败获取错误信息
                echo $file->getError();
            }




        } else {
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }

    public function local_and_qiniu_upload(){
        $this->assign('image',Db::name('image')->select());
        return $this->fetch();
    }

    public function unlink(){
        $url = "uploads/pre_pic/20170727/07c39dfa12c89b8fdb723b5e407d640b.jpg";
        unlink($url);
    }

    public function unlink_qiniu(){
        require_once APP_PATH . '/../vendor/qiniu/autoload.php';
        $accessKey = config('ACCESSKEY');
        $secretKey = config('SECRETKEY');
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = config('BUCKET');
        //初始化BucketManager
        $bucketMgr = new BucketManager($auth);
        //你要测试的空间， 并且这个key在你空间中存在
        $key = '07c39dfa12c89b8fdb723b5e407d640b.jpg';
        //删除$bucket 中的文件 $key
        $err = $bucketMgr->delete($bucket, $key);
        echo "\n====> delete $key : \n";
        if ($err !== null) {
            var_dump($err);
        } else {
            echo "Success!";
        }

    }


}




